package com.glsc.ngateway.platform.controller;

import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.platform.service.ValidateCodeService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Map;
import java.util.Properties;

@RestController
public class KaptchaController {
    Logger logger = LoggerFactory.getLogger(KaptchaController.class);

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @Resource
    ValidateCodeService validateCodeService;

    /**
     * 2、生成验证码
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        Map<String,String> randomValue = validateCodeService.getRandom();
        try {
            // 生产验证码字符串并保存到session中
            String createText = randomValue.get("redisStr");
            httpServletRequest.getSession().setAttribute("rightCode", createText);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = validateCodeService.getImage(randomValue.get("randomStr"));
            ImageIO.write(challenge, "png", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 3、校对验证码
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     */
    @RequestMapping("/imgvrifyControllerDefaultKaptcha")
    public PlatformResponse<?> imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest,
                                                                HttpServletResponse httpServletResponse) {

        try {
            String rightCode = (String) httpServletRequest.getSession().getAttribute("rightCode");
            String tryCode = httpServletRequest.getParameter("tryCode");
            logger.info("rightCode:" + rightCode + " ———— tryCode:" + tryCode);
            if (StringUtils.isEmpty(rightCode) || StringUtils.isEmpty(tryCode) || !rightCode.equals(tryCode)) {
                return PlatformResponse.failedMsg("错误的验证码");
            } else {
                return PlatformResponse.success();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return PlatformResponse.failedMsg("操作失败", e.getMessage());
        }
    }

}
